package com.ai.nsa;

import com.asiainfo.redis.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Feng Chen 2017/6/12.
 */
public class DefaultNSACache implements NSACache {

    private RedisClient redis;

    private int secTTL = DEFAULT_SECTTL;

    private static final int DEFAULT_SECTTL = 3600;

    private static final Logger logger = LoggerFactory.getLogger(DefaultNSACache.class);

    public RedisClient getRedis() {
        return redis;
    }

    public void setRedis(RedisClient redis) {
        this.redis = redis;
    }

    public int getSecTTL() {
        return secTTL;
    }

    public void setSecTTL(int secTTL) {
        this.secTTL = secTTL;
    }

    @Override
    public Object get(final String key) throws Exception {
        final Object[] result = {null};
        execute(new Executor() {

            @Override
            public void execute(RedisClient redis) throws Exception {
                result[0] = redis.getObject(key);
            }

        });

        return result[0];
    }

    @Override
    public void put(String key, Object value) throws Exception {
        put(key, value, DEFAULT_SECTTL);
    }

    @Override
    public void put(final String key, final Object value, final int secTTL) throws Exception {
        execute(new Executor() {
            @Override
            public void execute(RedisClient redis) throws Exception {
                redis.set(key, value, secTTL);
            }
        });
    }

    @Override
    public void push(final String key, final String value) throws Exception {
        logger.info("PUSH CACHE, KEY: {}, VALUE: {}", key, value);
        execute(new Executor() {
            @Override
            public void execute(RedisClient redis) throws Exception {
                redis.lpush(key, value);
            }
        });
    }

    @Override
    public String pop(final String key) throws Exception {
        logger.info("POP CACHE, KEY: {}", key);
        final String[] result = {null};
        execute(new Executor() {

            @Override
            public void execute(RedisClient redis) throws Exception {
                result[0] = redis.rpop(key);
            }

        });

        return result[0];
    }

    @Override
    public void delete(final String key) throws Exception {
        logger.info("DELETE CACHE, KEY: {}", key);
        execute(new Executor() {
            @Override
            public void execute(RedisClient redis) throws Exception {
                redis.del(key);
            }
        });
    }


    // SECTION: INNER HELPER

    private void execute(Executor executor) throws Exception {
        executor.execute(redis);
    }

    /////////////////////////////////////////////////

    private interface Executor {

        void execute(RedisClient redis) throws Exception;

    }


}
